package fem2.jlinalg;

import org.junit.Test;

import fem2.jnative.JPETSc;

public class JPETScTest {

	static {
		try {
			// System.load("/opt/openmpi/lib/libmpi.so.1");
			// System.load("/opt/openmpi/lib/libmpi.so");
			System.load("/opt/openmpi/lib/libmpi_f77.so.1");
			System.load("/opt/petsc/petsc-dev/lib/libpetsc.so");
			System.load("/home/hbui/workspace2/jni/JPETSc/Release/libJPETSc.so");
		} catch (UnsatisfiedLinkError e) {
			System.err
					.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n"
							+ e);
			System.exit(1);
		}
	}

	/**
	 * <pre>
	 * 
	 * SWIGEXPORT jint JNICALL Java_fem2_jnative_PETScJNI_JPETSc_1solve(JNIEnv *jenv,
	 * 		jclass jcls, jlong jarg1, jobject jarg1_, jdoubleArray jarg2) {
	 * 	jint jresult = 0;
	 * 	JPETSc *arg1 = (JPETSc *) 0;
	 * 	double *arg2;
	 * 	PetscErrorCode result;
	 * 
	 * 	(void) jenv;
	 * 	(void) jcls;
	 * 	(void) jarg1_;
	 * 	arg1 = *(JPETSc **) &jarg1;
	 * 
	 * 	jboolean isCopy1;
	 * 	arg2 = jenv->GetDoubleArrayElements(jarg2, &isCopy1);
	 * 
	 * 	result = (PetscErrorCode) (arg1)->solve(arg2);
	 * 	jresult = (jint) result;
	 * 
	 * 	jenv->ReleaseDoubleArrayElements(jarg2, arg2, JNI_COMMIT);
	 * 
	 * 	return jresult;
	 * }
	 * </pre>
	 */
	@Test
	public void test1() {
		int n = 3;
		double val[] = { 1, 1, 0, 1, 1, 1, 0, 1, 1 };
		double b[] = { 1, 2, 3 };
		double[] x = new double[n];

		String[] argv = new String[] { "-ksp_view" };
		JPETSc s = new JPETSc(argv);
		s.setSize(n);
		s.initialize();

		for (int i = 0; i < n; ++i) {
			for (int j = 0; j < n; ++j) {
				s.lhsAdd(i, j, val[n * i + j]);
			}
			s.rhsAdd(i, b[i]);
		}

		s.setPC("jacobi");

		s.solve(x);

		for (int i = 0; i < n; i++) {
			System.out.println(x[i]);
		}

		// s.finalize();
		s.delete();
	}
}
